import cTitle from 'components/title';
import { Toast } from 'vant';
import yzCommentInput from "components/ui_components/yz_commentInput";
import yzGoodsposter from "components/ui_components/yz_goodsPoster"

// var that = {};

// 将整数转换成 时：分：秒的格式
function realFormatSecond(second) {
  var secondType = typeof second;

  if (secondType === 'number' || secondType === 'string') {
    second = parseInt(second);

    var hours = Math.floor(second / 3600);
    second = second - hours * 3600;
    var mimute = Math.floor(second / 60);
    second = second - mimute * 60;

    return hours + ':' + ('0' + mimute).slice(-2) + ':' + ('0' + second).slice(-2);
  } else {
    return '0:00:00';
  }
}

export default {
  data() {
    return {
      is_report_enabled:false,
      showCommentInput: false,
      dataInfo: {
        audio_link: ''
      },

      // 是否有权限看
      isShow: 1,
      isPlay: true,
      readyState: 1,
      article_id: 0,
      codeUrl: '',

      sliderTime: 0,
      audio: {
        // 该字段是音频是否处于播放状态的属性
        playing: false,
        // 音频当前播放时长
        currentTime: 0,
        // 音频最大播放时长
        maxTime: 0,
        minTime: 0,
        step: 0.1
      },
      is_advs_type: false,
      like_num: 0,
      read_num: 0,
      is_liked: false,
      is_link: false,
      //微信要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮
      // 文章评论
      showCommentInput: false,
      commentInputOptions: {},
      replyName: "",
      commentPage: 1,
      commentList: [],
      last_page: 1,
      commenMember: [],
      commentListMore: [],
      keyInd: 0,
      comment_id: 0,
      comment: false,
      commentNum:0,
      //海报开关
      show_poster:false,
      // 海报弹窗显示
      posterShow:false,
      posterImg:'',
      isShowCode:true //判断是否免登录
    };
  },
  mounted() {
    this.$nextTick(() => {

    });
  },
  activated() {
    // that = this;
    this.init();
    this.getData();
    if(this.$route.query.task_type == 'article'){
      this.shareArticleTask();
    }
  },
  methods: {
    async showPost(){
      let { result, msg, data } = await $http.get('plugin.article.api.article.get-poster', {article_id:this.id},'');
      if(!result) return this.$toast(msg);
      this.posterShow = true;
      this.posterImg = data.poster;
    },
    async shareArticleTask(){
      let json = {
        record_id:this.$route.query.taskID,
        task_type:'article',
        day:this.$route.query.taskDay,
        task_record_id:this.article_id
      }
      let { result, msg, data } = await $http.get('plugin.task-package.frontend.daily-record.finish-task', json,'');
      if (result == 0) return this.$toast(msg);
    },
    init() {
      this.isPlay = true;
      this.readyState = 1;
      this.codeUrl = '';
      this.isShow = 1;
      this.article_id = this.$route.params.article_id;
      this.id = this.article_id;
    },
    getQrCode() {
      $http.get('member.member.getArticleQr', {}, "").then((response) => {
        if (response.result === 1) {
          this.codeUrl = response.data;
        } else {
          console.log(response.msg);
        }

      }, function (response) {
        console.log(response);
      });
    },
    //获取数据
    getData() {
      const that = this;
      let share_uid = this.fun.getKey("share_uid");
      share_uid = (this.fun.isTextEmpty(share_uid)) ? "" : share_uid;
      console.log("share_uid", share_uid);
      let json = {article_id: this.article_id, "share_uid": share_uid};

      $http.get('plugin.article.api.article.get-article', json, "").then((response) => {
        if (response.result === 1) {
          that.dataInfo = response.data;
          that.fun.setWXTitle(that.dataInfo.title);
          // that.initShare();
          that.is_advs_type = response.data.advs_type == 0 ? false : true;
          that.like_num = response.data.like_num + response.data.virtual_like_num;
          that.read_num = response.data.read_num + response.data.virtual_read_num;
          that.is_link = !that.fun.isTextEmpty(response.data.link);
          that.is_liked = response.data.liked == 0 ? false : true;
          that.show_poster = response.data.show_poster == 1?true:false;
          this.is_report_enabled = response.data.report_enabled == 0 ? false : true;
          if(response.data.comment){
            that.comment = response.data.comment;
            that.getComment();
          }
          let wxShareUrl = this.fun.getSiteRoot() + "/addons/yun_shop/?menu#/voiceDetail/"+ this.article_id +"?i=" + this.fun.getKeyByI();
          if(this.$route.query.taskID){
            wxShareUrl += `&taskID=${this.$route.query.taskID}&taskDay=${this.$route.query.taskDay}&task_type=article`;
          }
          if(this.dataInfo.detail_page_login_validator == '0'){
            this.isShowCode = false;
          } else {
            this.getQrCode();
          }
          this.fun.wxShare(
            "",
            { mid: this.fun.getKeyByMid() },
            {
              title: that.fun.isTextEmpty(that.dataInfo.title) ? '文章' : that.dataInfo.title,
              link:wxShareUrl,
              imgUrl:  that.fun.isTextEmpty(that.dataInfo.thumb) ? "" : that.dataInfo.thumb,
              description: that.fun.isTextEmpty(that.dataInfo.desc) ? "简介" : that.dataInfo.desc
            }
          );
        } else {
          this.isShow = 0;
          if (response.msg == "您尚未购买该文章内容,无法观看") {
            that.$dialog.alert({ message: response.msg }).then(()=>{
              that.$router.replace(that.fun.getUrl("payList", { id: that.id }));
            });
          }else{
            that.$dialog.alert({message:response.msg}).then(()=>{
              that.$router.go(-1);
            });
          }

        }

      }, function (response) {
        console.log(response);
      });
    },
    //查看营销
    toAdvs() {
      if (!this.fun.isTextEmpty(this.dataInfo) && this.fun.isTextEmpty(this.dataInfo.advs_link)) {
        return;
      }
      window.location.href = this.fun.funHrefFilters(this.dataInfo.advs_link);
    },
    //  -----------------------  文章评论 ---------------
    getComment() {
      $http
        .post(
          "plugin.article.api.comment.comment-list",
          {
            page: this.commentPage,
            article_id: this.id
          },
          ""
        )
        .then(response => {
          if (response.result == 1) {
            this.commentList = response.data.list.data;
            for (let i = 0; i < this.commentList.length; i++) {
              if (this.commentList[i].reply_num > 0) {
                this.$set(this.commentList[i], "commentShow", true);
              } else {
                this.$set(this.commentList[i], "commentShow", false);
              }
              this.$set(this.commentList[i], "commenMorePage", "1");
            }
            this.last_page = response.data.list.last_page;
            this.commenMember = response.data.member;
            this.commentNum = response.data.num;
          } else {
            Toast(response.msg);
          }
        });
    },
    watchImg(item){
      this.imgList = item;
      this.showImg = true;
    },
    getMore() {
      this.commentPage = this.commentPage + 1;
      $http
        .post(
          "plugin.article.api.comment.comment-list",
          {
            page: this.commentPage,
            article_id: this.id
          },
          ""
        )
        .then(response => {
          if (response.result == 1) {
            let dataMore = response.data.list.data;
            this.commentList = this.commentList.concat(dataMore);
            for (let i = 0; i < this.commentList.length; i++) {
              if (this.commentList[i].reply_num > 0) {
                this.$set(this.commentList[i], "commentShow", true);
              } else {
                this.$set(this.commentList[i], "commentShow", false);
              }
              this.$set(this.commentList[i], "commenMorePage", 1);
            }
            console.log(this.commentList);
            this.last_page = response.data.list.last_page;
          } else {
            Toast(response.msg);
          }
        });
    },
    // 加载子评论
    moreCommentLis(id, ind) {
      let url = "plugin.article.api.comment.get-replys";
      // 当前主评论的加载页数 is_page
      let is_page = Number(this.commentList[ind].commenMorePage);
      let dataJson = {
        page: is_page,
        comment_id: id
      };
      $http.post(url, dataJson, "").then(response => {
        if (response.result == 1) {
          let child = response.data.data;
          if (is_page >= 1 && this.commentList[ind].child) {
            child = this.commentList[ind].child.concat(child);
          }
          this.$set(this.commentList[ind], "child", child);
          let mun = this.commentList[ind].reply_num - response.data.data.length;
          this.$set(this.commentList[ind], "reply_num", mun);
          let moreLast_page = response.data.last_page;
          if (is_page >= moreLast_page) {
            is_page = 1;
          } else {
            is_page = is_page + 1;
          }
          this.$set(this.commentList[ind], "commenMorePage", is_page);
        } else {
          Toast(response.msg);
        }
      });
    },
    // 发送
    subMainBtn(e) {
      if (e) {
        console.log("1111111111111111111", e);
        this.showCommentInput = false;
        this.getReplyComments(e);
      }
    },
    // 发送请求
    getReplyComments(e) {
      let that = this;
      let url;
      let dataJson = {
        images: JSON.stringify(e.imgs),
        content: e.text
      };
      console.log("e.options.type", e.options.type);
      // main 是创建评论  reply 是回复评论
      if (e.options.type == "reply") {
        url = "plugin.article.api.comment.reply-comment";
        dataJson.comment_id = that.replyId;
      } else if (e.options.type == "main") {
        url = "plugin.article.api.comment.create-comment";
        dataJson.article_id = that.id;
      }
      $http.post(url, dataJson,'').then(response => {
        if (response.result == 1) {
          if (e.options.type == "main") {
            that.commentPage = 1;
            that.getComment();
          } else {
            that.updateInfo("getReply", response.data, that.keyInd);
          }
          Toast(response.msg);
          console.log(response.data);
        } else {
          Toast(response.msg);
        }
      });
    },
    // 回复后更新数据
    updateInfo(key, data, ind) {
      let arr = [];
      arr.push(data);
      if (this.commentList[ind].child) {
        this.commentList[ind].child.unshift(arr[0]);
      } else {
        this.$set(this.commentList[ind], "child", arr);
      }
    },
    subMainCommentBtn() {
      console.log(" main 是创建评论");
      this.showCommentInput = true;
      this.commentInputOptions = {
        type: "main"
      };
    },
    replyBtn(name, item, ind) {
      this.keyInd = ind;
      this.replyId = "";
      // 回复别人的评论
      this.replyId = item.id;
      this.comment_id = item.comment_id == 0 ? item.comment_id : item.id;
      this.replyName = name;
      this.showCommentInput = true;
      this.commentInputOptions = {
        type: "reply",
        placeholder: "请输入你的回复吧",
        route:"articleContent",
        replyName:this.replyName
      };
      this.commentManagement = false;
    },
    delComment(item, ind, index, key) {
      let id;
      let myUid = window.localStorage.uid;
      id = item.id;
      if (key == "child") {
        console.log(item, "子组件");
        if(item.uid == myUid){
          console.log('可以删除 子评论');
          this.delRequst(id,ind,index,key);
        }
      } else {
        if (item.uid == myUid) {
          console.log('可以删除 主评论');
          this.delRequst(id,ind,index,key);
        }
      }

    },
    delRequst(id,ind,index,key) {
      this.$dialog
        .confirm({ message: "是否删除评论?" })
        .then(() => {
          $http
            .post("plugin.article.api.comment.del", {
              comment_id: id
            },'')
            .then(response => {
              if (response.result == 1) {
                if (key == 'child') {
                  this.commentList[ind].child.splice(index, 1);
                  this.$set(this.commentList[ind], "child", this.commentList[ind].child);
                } else {
                  this.commentList.splice(ind, 1);
                }
                Toast(response.data);
              } else {
                Toast(response.msg);
              }
            });
        })
        .catch(() => {});
    },
    //举报
    report() {
      this.$router.push(this.fun.getUrl("noticeReport", { id: this.id }));
    },
    //阅读原文
    link() {
      window.location.href = this.fun.funHrefFilters(this.dataInfo.link);
    },
    //点赞
    like(like_num) {
      let that = this;
      let json = { article_id: this.id };

      $http.get("plugin.article.api.article.like", json, "").then(
        function(response) {
          if (response.result === 1) {
            if (response.data.liked == 1) {
              that.is_liked = true;
              that.like_num = like_num + 1;
              Toast("点赞成功");
            } else {
              that.is_liked = false;
              that.like_num = like_num - 1;
              if (that.like_num < 0) {
                that.like_num = 0;
              }
              Toast("取消点赞");
            }
          }
        },
        function(response) {
          console.log(response);
        }
      );
    },
    //初始化分享设置
    initShare() {
      let that = this;
      let _url = document.location.href;
      let json = {url: _url, "mid": this.fun.getKeyByMid()};
      $http.post('member.member.wxJsSdkConfig', json).then(function (response) {
        if (response.result === 1) {
          that.share(response.data);
        } else {
          that.$dialog.alert({message:response.msg});

        }
      }, function (response) {
        console.log(response);
      });
    },

    //组装分享设置
    share(data) {
      let that = this;
      wx.config(data.config);
      wx.ready(function () {

        let _title = (that.fun.isTextEmpty(that.dataInfo.title)) ? '文章' : that.dataInfo.title;
        let _link = document.location.href;
        _link = that.fun.isMid(_link, data.info.uid);

        let _imgUrl = (that.fun.isTextEmpty(that.dataInfo.thumb)) ? "" : that.dataInfo.thumb;
        let _desc = (that.fun.isTextEmpty(that.dataInfo.desc)) ? "简介" : that.dataInfo.desc;
        wx.showOptionMenu();
        wx.onMenuShareTimeline({
          title: _title, // 分享标题
          link: _link, // 分享链接
          imgUrl: _imgUrl, // 分享图标
          success: function () {
            Toast("分享成功");
          },
          cancel: function () {
            Toast("取消分享");
          }
        });

        wx.onMenuShareAppMessage({
          title: _title, // 分享标题
          desc: _desc, // 分享描述
          link: _link, // 分享链接
          imgUrl: _imgUrl, // 分享图标
          type: 'link', // 分享类型,music、video或link，不填默认为link
          dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
          success: function () {
            Toast("分享成功");
          },
          cancel: function () {
            Toast("取消分享");
          }
        });

      });
    },
    // 控制音频的播放与暂停
    startPlayOrPause() {
      this.readyState = this.$refs.audio.readyState;
      this.audio.playing ? this.isPlay = true : this.isPlay = false;
      return this.audio.playing ? this.pause() : this.play();
    },
    // 播放音频
    play() {
      this.$refs.audio.play();
    },
    // 暂停音频
    pause() {
      this.$refs.audio.pause();
    },
    // 当音频播放
    onPlay() {
      this.audio.playing = true;
    },
    // 当音频暂停
    onPause() {
      this.audio.playing = false;
    },
    handleFocus() {
      console.log('focues');
    },
    error(e) {
      this.$dialog.alert({message:'音频出错了'});

    },
    // 当加载语音流元数据完成后，会触发该事件的回调函数
    // 语音元数据主要是语音的长度之类的数据
    onLoadedmetadata(res) {
      this.readyState = this.$refs.audio.readyState;
      this.audio.maxTime = parseInt(res.target.duration);
    },
    // 当timeupdate事件大概每秒一次，用来更新音频流的当前播放时间
    // 当音频当前时间改变后，进度条也要改变
    onTimeupdate(res) {
      this.audio.currentTime = res.target.currentTime;
      this.sliderTime = parseInt(this.audio.currentTime / this.audio.maxTime * 100);
      if(this.sliderTime>=100){
        this.isPlay = true;
      }
    },

    // 进度条格式化toolTip
    formatProcessToolTip(index = 0) {
      index = parseInt(this.audio.maxTime / 100 * index);
      return '进度条: ' + realFormatSecond(index);
    },

    handleTouchStart(e) {
      this.setValue(e.touches[0]);

      document.addEventListener('touchmove', this.handleTouchMove);
      document.addEventListener('touchup', this.handleTouchEnd);
      document.addEventListener('touchend', this.handleTouchEnd);
      document.addEventListener('touchcancel', this.handleTouchEnd);
      // e.preventDefault();
      // this.onDragStart(e);
    },
    handleTouchMove(e) {
      this.setValue(e.changedTouches[0]);
    },
    handleTouchEnd(e) {
      this.setValue(e.changedTouches[0]);
      document.removeEventListener('touchmove', this.handleTouchMove);
      document.removeEventListener('touchup', this.handleTouchEnd);
      document.removeEventListener('touchend', this.handleTouchEnd);
      document.removeEventListener('touchcancel', this.handleTouchEnd);
      // this.onDragStop(e);
    },
    // 从点击位置更新 value
    setValue(e) {
      const {
        maxTime,
        minTime,
        step
      } = this.audio;
      let value = (e.clientX - this.$refs.slider.offsetLeft) / this.$refs.slider.offsetWidth * (maxTime - minTime);
      value = Math.round(value / step) * step + minTime;
      value = parseFloat(value.toFixed(5));

      if (value > maxTime) {
        value = maxTime;
      } else if (value < minTime) {
        value = minTime;
      }
      this.$refs.audio.currentTime = value;
    },
    // 拖动进度条，改变当前时间，index是进度条改变时的回调函数的参数0-100之间，需要换算成实际时间
    changeCurrentTime(index) {
      console.log('拖动进度条');
      this.$refs.audio.currentTime = parseInt(index / 100 * this.audio.maxTime);
    }
  },
  filters: {
    // 将整数转化成时分秒
    formatSecond(second = 0) {
      return realFormatSecond(second);
    }
  },
  components: {cTitle,yzCommentInput, yzGoodsposter}
};